package com.bajiao.app.controller.order;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bajiao.app.base.AppBaseController;
import com.bajiao.common.api.vo.RestResult;
import com.bajiao.common.exception.DataHandleException;
import com.bajiao.common.util.FastJsonHelper;
import com.bajiao.common.web.entity.TableDataInfo;
import com.bajiao.dto.order.ConfirmOrderRequest;
import com.bajiao.dto.order.CreateOrderRequest;
import com.bajiao.entity.order.EncodeMenuOrderDetails;
import com.bajiao.entity.order.Order;
import com.bajiao.entity.user.User;
import com.bajiao.service.cart.CartService;
import com.bajiao.service.order.OrderService;
import com.bajiao.service.user.UserService;
import com.bajiao.vo.cart.CartResponse;
import com.bajiao.vo.coupon.CouponDetailsResponse;
import com.bajiao.vo.order.ConfirmOrderResponse;
import com.bajiao.vo.order.OrderDetailsResponse;
import com.bajiao.vo.order.OrderResponse;
import com.bajiao.vo.store.StoreStatResponse;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "商品订单接口")
@RestController
@RequestMapping("/api/v1/order")
public class RestOrderController extends AppBaseController {

    @Resource
    private OrderService orderService;
    @Resource
    private CartService cartService;

    @PostMapping(value = "/confirm")
    @ApiOperation(value = "确认订单")
    public RestResult<ConfirmOrderResponse> confirm(@ModelAttribute("userId") String userId,
                                                    ConfirmOrderRequest request) {
        if (StrUtil.isBlank(userId))
            return tokenOverdue();
        if (StrUtil.hasBlank(request.getLongitude(), request.getLatitude()))
            throw new DataHandleException("未获取到位置信息");
        if (StrUtil.isBlank(request.getStoreId()))
            throw new DataHandleException("请选择店铺");
        List<String> idList = Arrays.asList(request.getCartIds().split(StringPool.COMMA));
        if (CollectionUtil.isEmpty(idList))
            throw new DataHandleException("请选择购买商品");

        ConfirmOrderResponse response = orderService.confirm(userId, request);
        response.setCartIds(request.getCartIds());
        return success(response);
    }

    @PostMapping(value = "/center/confirm")
    @ApiOperation(value = "订单中心去支付")
    public RestResult<ConfirmOrderResponse> centerConfirm(@ModelAttribute("userId") String userId,
                                                          ConfirmOrderRequest request) {
        if (StrUtil.isBlank(userId))
            return tokenOverdue();
        if (StrUtil.hasBlank(request.getLongitude(), request.getLatitude()))
            throw new DataHandleException("未获取到位置信息");
        if (StrUtil.isBlank(request.getStoreId()))
            throw new DataHandleException("请选择店铺");
        if (StrUtil.isBlank(request.getOrderNo()))
            throw new DataHandleException("请选择订单");
        ConfirmOrderResponse response = orderService.centerConfirm(userId, request);
        response.setOrderNo(request.getOrderNo());
        return success(response);
    }

    @PostMapping(value = "/to/pay")
    @ApiOperation(value = "支付")
    public RestResult toPay(@ModelAttribute("user") User user,
                            CreateOrderRequest params,
                            HttpServletRequest request) {
        if (ObjectUtil.isNull(user))
            return tokenOverdue();
        if (params.getType() == 1) {
            List<String> idList = Arrays.asList(params.getCartIds().split(StringPool.COMMA));
            if (CollectionUtil.isEmpty(idList))
                throw new DataHandleException("请选择购买商品");
        } else if(params.getType() == 2) {
            if (StrUtil.isBlank(params.getOrderNo()))
                throw new DataHandleException("请选择订单");
        } else
            throw new DataHandleException("结算方式错误");

        if (params.getPayWay() < 1 || params.getPayWay() > 2)
            throw new DataHandleException("支付方式错误");
        if (params.getPayWay() == 2 && StrUtil.isBlank(params.getSource()))
            throw new DataHandleException("请选择支付渠道");
        Object result = orderService.toPay(user, params, request);
        return success("", result);
    }

    @GetMapping(value = "/page")
    @ApiOperation(value = "订单分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "status", value = "99-全部 0-待支付 1-待使用 2-已使用 7-售后 9-已取消", defaultValue = "99", dataType = "Integer", required = true),
    })
    public RestResult<TableDataInfo<OrderResponse>> getOrderPage(@ModelAttribute("userId") String userId,
                                                                 @RequestParam(value = "status", defaultValue = "99") Integer status) {
        if (StrUtil.isBlank(userId))
            return tokenOverdue();
        startPage();
        List<OrderResponse> orderPage = orderService.getOrderPage(userId, status);
        return success(getDataTable(orderPage));
    }

    @PostMapping(value = "/cancel")
    @ApiOperation(value = "取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", dataType = "String", required = true)
    })
    public RestResult cancel(@ModelAttribute("userId") String userId,
                             @RequestParam("orderNo") String orderNo) {
        if (StrUtil.isBlank(userId))
            return tokenOverdue();
        orderService.cancel(userId, orderNo);
        return success();
    }

    @PostMapping(value = "/ask/refund")
    @ApiOperation(value = "申请退款")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", dataType = "String", required = true),
            @ApiImplicitParam(name = "reason", value = "退款原因", dataType = "String")
    })
    public RestResult askRefund(@ModelAttribute("userId") String userId,
                                @RequestParam("orderNo") String orderNo,
                                @RequestParam(value = "reason", required = false) String reason) {
        if (StrUtil.isBlank(userId))
            return tokenOverdue();
        orderService.askRefund(userId, orderNo, reason);
        return success("", orderNo);
    }

    @PostMapping(value = "/details")
    @ApiOperation(value = "订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", dataType = "String", required = true)
    })
    public RestResult<OrderDetailsResponse> getDetails(@ModelAttribute("user") User user,
                                                       @RequestParam("orderNo") String orderNo) {
        if (ObjectUtil.isNull(user))
            return tokenOverdue();
        OrderDetailsResponse response = orderService.getDetails(user.getId(), orderNo);
        response.setNickname(user.getNickname());
        return success(response);
    }

    @GetMapping(value = "/discount/tip")
    @ApiOperation(value = "获取优惠提示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "店铺id", dataType = "String", required = true)
    })
    public RestResult<String> getDiscountTips(@ModelAttribute("userId") String userId,
                                              @RequestParam(value = "storeId") String storeId) {
        if (StrUtil.isBlank(userId))
            return tokenOverdue();
        String tip = orderService.getDiscountTips(userId, storeId);
        return success("", tip);
    }

    @GetMapping(value = "/cart/amount")
    @ApiOperation(value = "计算购物车价格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "店铺id", dataType = "String", required = true)
    })
    public RestResult<String> getCardAmount(@ModelAttribute("userId") String userId,
                                            @RequestParam(value = "storeId") String storeId) {
        if (StrUtil.isBlank(userId))
            return tokenOverdue();
        List<CartResponse> cartList = cartService.getUserCartList(userId, storeId, null);
        List<String> cartIdList = cartList.stream().map(CartResponse::getId).collect(Collectors.toList());
        Map<String, String> resultMap = orderService.getCartAmount(userId, storeId, String.join(StringPool.COMMA, cartIdList));
        resultMap.put("cartIds", String.join(StringPool.COMMA, cartIdList));
        return success(resultMap);
    }

}
